package com.lanhe.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.StringUtils;
import com.lanhe.common.utils.qingchuang.QingChuangUtil;
import com.lanhe.common.utils.qingchuang.vo.QingChuangInfoVO;
import com.lanhe.common.utils.qingchuang.vo.QingChuangListVO;
import com.lanhe.product.domain.LhQingchuangProduct;
import com.lanhe.product.domain.LhQingchuangProductDetails;
import com.lanhe.product.mapper.LhQingchuangProductMapper;
import com.lanhe.product.service.ILhQingchuangProductDetailsService;
import com.lanhe.product.service.ILhQingchuangProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 清创产品(LhQingchuangProduct)表服务实现类
 *
 * @author zhanggl
 * @since 2023-12-20 12:51:13
 */
@Service
public class LhQingchuangProductServiceImpl extends ServiceImpl<LhQingchuangProductMapper, LhQingchuangProduct> implements ILhQingchuangProductService {

	@Autowired
	private LhQingchuangProductMapper productMapper;

	@Autowired
	private ILhQingchuangProductDetailsService productDetailsService;

	@Autowired
	private QingChuangUtil qingChuangUtil;



	/**
	 * 拉取清创产品数据
	 *
	 * @author zhanggl
	 * @date 2023/12/20
	 */
	@Override
	public void pullProduct() {
		try {
			String qingChuangProductList = qingChuangUtil.getQingChuangProductList("", null);
			QingChuangListVO qingChuangListVO = JSONObject.parseObject(qingChuangProductList, QingChuangListVO.class);
			if (!Constants.GeneralIntType.ONE.equals(qingChuangListVO.getCode())) {
				throw new ServiceException("获取列表异常", HttpStatus.ERROR);
			}
			for (QingChuangListVO.DataBean datum : qingChuangListVO.getData()) {

				String resource = qingChuangUtil.getQingChuangProductInfo(datum.getNumber());
				QingChuangInfoVO qingChuangInfoVO = JSONObject.parseObject(resource, QingChuangInfoVO.class);
				if (!Constants.GeneralIntType.ONE.equals(qingChuangInfoVO.getCode())) {
					throw new ServiceException("返回详情异常", HttpStatus.ERROR);
				}

				// 更新主表数据
				saveProductData(datum);

				// 更新详情信息
				saveProductDetailData(qingChuangInfoVO.getData());
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private void saveProductData(QingChuangListVO.DataBean datum){

		LhQingchuangProduct product = new LhQingchuangProduct();
		product.setId(datum.getId());
		product.setCname(datum.getCname());
		product.setTitle(datum.getTitle());
		product.setSubtitle(datum.getSubtitle());
		product.setTag(datum.getTag());
		product.setNumber(datum.getNumber());
		product.setThmub(datum.getThmub());
		product.setPolicy(datum.getPolicy());
		product.setCourse(datum.getCourse());
		product.setType(datum.getType());
		product.setLinktype(datum.getLinktype());
		product.setFormtype(datum.getFormtype());
		product.setFormTitle(datum.getForm_title());
		product.setFormTemplate(datum.getForm_template());
		product.setSubTemplateTitle(datum.getSub_title());
		product.setSubTemplate(datum.getSub_template());
		product.setSort(datum.getSort());
		product.setStatus(datum.getStatus());
		product.setOvertime(datum.getOvertime());
		product.setApplytype(datum.getApplytype());
		product.setIsopen(datum.getIsopen());
		product.setTask(JSON.toJSONString(datum.getTask()));

		BigDecimal brokerage = new BigDecimal("0.00");
		if (ObjectUtil.isNotEmpty(datum.getTask())) {
			double macPrice = datum.getTask().stream()
					.mapToDouble(QingChuangListVO.DataBean.TaskBean::getPrice)
					.max()
					.orElse(0);
			if (macPrice > 0) {
				brokerage = new BigDecimal(macPrice);
			}
		}

		product.setBrokerage(brokerage);
		Instant instant = Instant.ofEpochSecond(datum.getCreatetime());
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		Date createTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

		Instant instant1 = Instant.ofEpochSecond(datum.getUpdatetime());
		LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());
		Date updateTime = Date.from(localDateTime1.atZone(ZoneId.systemDefault()).toInstant());

		Instant instant2 = Instant.ofEpochSecond(datum.getUpdatetime());
		LocalDateTime localDateTime2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());
		Date deleteTime = Date.from(localDateTime2.atZone(ZoneId.systemDefault()).toInstant());

		product.setCreatetime(createTime);
		product.setUpdatetime(updateTime);
		product.setDeletetime(deleteTime);
		saveProduct(product);
	}

	private void saveProductDetailData(QingChuangInfoVO.DataBean datum){

		LhQingchuangProductDetails productDetails = new LhQingchuangProductDetails();
		productDetails.setId(datum.getId());
		productDetails.setTitle(datum.getTitle());
		productDetails.setSubtitle(datum.getSubtitle());
		productDetails.setTag(datum.getTag());
		productDetails.setNumber(datum.getNumber());
		productDetails.setThmub(datum.getThmub());
		productDetails.setPolicy(datum.getPolicy());
		productDetails.setCourse(datum.getCourse());
		productDetails.setType(datum.getType());
		productDetails.setFormTitle(datum.getForm_title());
		productDetails.setFormTemplate(JSON.toJSONString(datum.getForm_template()));
		productDetails.setSubTemplateTitle(datum.getSub_title());
		productDetails.setSubTemplate(JSON.toJSONString(datum.getSub_template()));
		productDetails.setSort(datum.getSort());
		productDetails.setStatus(datum.getStatus());
		productDetails.setOvertime(datum.getOvertime());
		productDetails.setApplytype(datum.getApplytype());
		productDetails.setTask(JSON.toJSONString(datum.getTask()));

		BigDecimal brokerage = new BigDecimal("0.00");
		if (ObjectUtil.isNotEmpty(datum.getTask())) {
			double macPrice = datum.getTask().stream()
					.mapToDouble(QingChuangInfoVO.DataBean.TaskBean::getPrice)
					.max()
					.orElse(0);
			if (macPrice > 0) {
				brokerage = new BigDecimal(macPrice);
			}
		}

		productDetails.setBrokerage(brokerage);
		productDetails.setIsstop(datum.getIsstop());
		productDetails.setApplyExpectTime(datum.getApply_expect_time());
		productDetails.setRemind(datum.getRemind());
		productDetails.setRemindVersion(datum.getRemind_version());
		productDetails.setVideoMaterial(JSON.toJSONString(datum.getVideo_material()));
		productDetails.setShowMaterial(datum.getShow_material());
		productDetails.setSpins(datum.getSpins());
		productDetails.setLinknum(datum.getLinknum());
		Instant instant = Instant.ofEpochSecond(datum.getCreatetime());
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		Date createTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

		Instant instant1 = Instant.ofEpochSecond(datum.getUpdatetime());
		LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault());
		Date updateTime = Date.from(localDateTime1.atZone(ZoneId.systemDefault()).toInstant());

		Instant instant2 = Instant.ofEpochSecond(datum.getUpdatetime());
		LocalDateTime localDateTime2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());
		Date deleteTime = Date.from(localDateTime2.atZone(ZoneId.systemDefault()).toInstant());

		productDetails.setCreatetime(createTime);
		productDetails.setUpdatetime(updateTime);
		productDetails.setDeletetime(deleteTime);
		productDetailsService.saveProductDetails(productDetails);
	}

	/**
	 * 保存产品信息
	 *
	 * @param product 实体
	 * @return void
	 * @author zhanggl
	 * @date 2023/12/20
	 */
	private LhQingchuangProduct saveProduct(LhQingchuangProduct product) {
		LhQingchuangProduct productRet = getProductByIdAndNumber(product.getId(), product.getNumber());
		if (ObjectUtil.isNotEmpty(productRet)){
			productMapper.updateById(product);
		} else {
			productMapper.insert(product);
		}
		return product;
	}

	/**
	 * 获取产品信息
	 *
	 * @param id 产品id
	 * @param number 产品编号
	 * @return LhQingchuangProduct 产品信息
	 * @author zhanggl
	 * @date 2023/12/20
	 */
	private LhQingchuangProduct getProductByIdAndNumber(Long id, String number) {
		LambdaQueryWrapper<LhQingchuangProduct> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhQingchuangProduct::getId, id);
		queryWrapper.eq(LhQingchuangProduct::getNumber, number);
		return productMapper.selectOne(queryWrapper);
	}

	/**
	 * 列表数据
	 *
	 * @param product 实体
	 * @return java.util.List<com.lanhe.product.domain.LhQingchuangProduct>
	 * @author zhanggl
	 * @date 2023/12/20
	 */
	@Override
	public List<LhQingchuangProduct> selectProductList(LhQingchuangProduct product) {
		LambdaQueryWrapper<LhQingchuangProduct> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.like(StringUtils.isNotBlank(product.getTitle()),LhQingchuangProduct::getTitle, product.getTitle());
		queryWrapper.eq(LhQingchuangProduct::getStatus,Constants.GeneralIntType.ONE);
		queryWrapper.eq(ObjectUtil.isNotNull(product.getType()),LhQingchuangProduct::getType, product.getType());
		queryWrapper.orderByDesc(LhQingchuangProduct::getId);
		return productMapper.selectList(queryWrapper);
	}

}

